<?php
include("session.php");
include("config.php");


function checkPassword($pwd, &$errors)
{
    $pass_minlength = 10;
    $errors_init = $errors;

    if (strlen($pwd) < $pass_minlength) {
        $errors[] = sprintf( RLang("err_pass_minlen"), $pass_minlength);
    }

    if (!preg_match("#[0-9]+#", $pwd)) {
        $errors[] = RLang("err_pass_number");
    }

    if (!preg_match("#[a-z]+#", $pwd)) {
        $errors[] = RLang("err_pass_lower");
    }

    if (!preg_match("#[A-Z]+#", $pwd)) {
        $errors[] = RLang("err_pass_uper");
    }

    return ($errors == $errors_init);
}

$id = 0;
if (isset($_GET['id']))
    $id = $_GET['id'];
$site = "write_user.php";
if (!isset($_POST['name']) || !isset($_POST['pass']) || !isset($_POST['level'])) {
    $_SESSION['msgtype'] = "error";
    $_SESSION['msg'] = sprintf(RLang("err_post_field_missing"), "name|pass|level", $site);
    header("Location: user_list.php");
    exit();
}

$pass = $_POST['pass'];
$errors = array();
$passchanged = strcmp($pass, DEFAULT_PWMASK) != 0;
if (($passchanged || $id == 0) && !checkPassword($pass, $errors)) {
    $_SESSION['msgtype'] = "error";
    $_SESSION['msg'] = implode("\r\n", $errors);
    header("Location: edit_user.php?id=" . $id);
    exit();
}


if ($id == 0) {
    if (!validate(LEVEL_CREATE_USER, $site, $db, "user_list.php"))
        exit();
    $passhash = hash('sha512', $_POST['pass'], false);
    $sql = "INSERT INTO user(name, pass, level, created) VALUES( ?, ?, ?, NOW())";
    $result = get_db_result($db, $sql, "ssi", $_POST['name'], $passhash, $_POST['level']);
} else {
    if (!validate(LEVEL_EDIT_USER, $site, $db, "user_list.php"))
        exit();
    if ($passchanged) {
        $passhash = hash('sha512', $_POST['pass'], false);
        $sql = "UPDATE user SET name=?, pass=?, level=? WHERE id = ?";
        $result = get_db_result($db, $sql, "ssii", $_POST['name'], $passhash, $_POST['level'],  $id);
    } else {
        $sql = "UPDATE user SET name=?, level=? WHERE id = ?";
        $result = get_db_result($db, $sql, "sii", $_POST['name'], $_POST['level'],  $id);
    }
}
if (!$result) {
    echo ($sql . " ");
    die(mysqli_error($db));
} else {
    $_SESSION['msgtype'] = "msg";
    $_SESSION['msg'] = sprintf( RLang("msg_save_success"), RLang("user"));
    header("Location: user_list.php");
    exit();
}
